<template>
  <el-drawer
    v-model="dialogVisible"
    :show-close="false"
    size="600px"
    :wrapperClosable="false"
    :before-close="handleClose"
    @open="handleOpen">
    <template #header>
      <div class="search-custom-title-nav">
        <p class="title">{{title}}</p>
        <div>
          <el-button @click="handleClose(true)">关闭</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
    <el-scrollbar class="search-main-wrap">
      <div>
        <el-form
          ref="formRef" :model="form"
          :rules="rules"
          label-suffix="："
          label-position="top"
          label-width="100px"
          inline>
          <el-form-item label="角色名称" prop="name">
            <el-input
              v-model="form.name"
              size="small"
              clearable
              v-trim
              class="input-width"
              maxlength="15"
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model.trim="form.description"
              size="small"
              clearable
              v-trim
              class="input-width"
              maxlength="25"
              show-word-limit
              placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <div class="input-width">
              <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                :active-value="1"
                :inactive-value="0"
              ></el-switch>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <div class="module-title">权限设置</div>
        <div class="tree-wrap">
          <el-skeleton v-if="getResourceLoading"/>
          <el-tree
            v-else
            ref="resourceTreeRef"
            node-key="fid"
            :data="resourceList"
            show-checkbox
            :default-checked-keys="defaultResourceCheckedKeys"
            :props="defaultProps"></el-tree>
        </div>
      </div>
    </el-scrollbar>
  </el-drawer>
</template>

<script setup>
import { ref, defineProps, defineEmits, nextTick, computed } from 'vue'
import { useDialogCommonData, emitBaseEventList } from '@/composables/dialog-common'
import { awaitWrap, elFormValidate } from '@/utils'
import { SUCCESS_CODE } from '@/constants'
import { ElMessage } from 'element-plus'
import { getRoleResource, saveRoleInfo } from '@/api/role-management'
import { PERMISSION_LIST } from '@/constants/mock-login-data'

// ---------------------props-------------------
const props = defineProps({
  visible: Boolean, // 可见性
  pdata: { // 数据，同defaultForm表单
    type: Object,
    default () {
      return null
    }
  }
})

// emit
const emit = defineEmits([...emitBaseEventList])

// form组件实例
const formRef = ref() // this.$refs.form

// 是否是编辑
const isEdit = computed(() => !!props.pdata)

// ---------------------el-Dialog组件需要一些参数-------------------
const { dialogVisible, handleClose } = useDialogCommonData(props, emit)
const title = ref('')
// 打开
const handleOpen = () => {
  title.value = isEdit.value ? '编辑' : '新增'
  initForm()
  initResource()
}

// ---------------------form表单内容-------------------
// 默认表格内容
const defaultForm = {
  fid: '',
  name: '', // 角色名称
  description: '', // 角色描述
  status: 1
}

const form = ref({ ...defaultForm })
const rules = ref({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
})
// 初始化form
const initForm = () => {
  form.value = isEdit.value ? { ...props.pdata } : { ...defaultForm }
  nextTick(formRef.value.clearValidate)
}

// ---------------------树形权限相关内容-------------------
// 树形实例
const resourceTreeRef = ref(null)
// 权限资源数据列表
const resourceList = ref([])
// 默认选中的数据列表
const defaultResourceCheckedKeys = ref([])
// 选中的资源id
const resourceChecked = ref([])
// 树形组件prop设置
const defaultProps = {
  label: 'fname',
  children: 'fchildren'
}
// 获取资源loading
const getResourceLoading = ref(false)

// 初始化资源
const initResource = () => {
  resourceList.value = []
  resourceChecked.value = []
  defaultResourceCheckedKeys.value = []
  // 真实数据请用这个方法
  const isMock = false
  if (isMock) {
    // 假数据
    getMockData()
  } else {
    getResourceList()
  }
}
// 获取资源
const getResourceList = async () => {
  getResourceLoading.value = true
  const { res } = await awaitWrap(getRoleResource(props.pdata?.fid || ''))
  if (res?.statusCode === SUCCESS_CODE) {
    const treeData = res.data || []
    setTimeout(() => {
      resourceList.value = treeData
      dealRoleResourceTree(treeData)
    }, 100)
  }
  getResourceLoading.value = false
}
// 假资源数据
const getMockData = () => {
  const treeData = PERMISSION_LIST
  setTimeout(() => {
    resourceList.value = treeData
    dealRoleResourceTree(treeData)
  }, 100)
}
// 获取当前勾选的树的ids
const getResourceCheckedNode = () => {
  const ref = resourceTreeRef.value
  return [...ref.getCheckedKeys(false), ...ref.getHalfCheckedKeys()]
}

// 递归处理功能权限
const dealRoleResourceTree = (tree) => {
  tree.forEach(item => {
    if (!item.children && item.fchecked) {
      defaultResourceCheckedKeys.value.push(item.fid)
      resourceChecked.value.push(item.fid)
    }
    if (item.children && item.children.length > 0) {
      dealRoleResourceTree(item.children)
    }
  })
}

// ---------------------提交数据-------------------
const submitLoading = ref(false)
// 设置提交参数
const setParams = () => {
  const f = form.value
  return {
    fid: f.fid,
    fname: f.name,
    fdescription: f.description,
    fstatus: f.status,
    fresourceIdList: resourceChecked.value
  }
}
const handleConfirm = async () => {
  resourceChecked.value = getResourceCheckedNode()
  if (resourceChecked.value.length === 0) {
    ElMessage.error('最少选择一条权限')
    return
  }
  await elFormValidate(formRef.value)
  const params = setParams()
  submitLoading.value = true
  const { res } = await awaitWrap(saveRoleInfo(params))
  if (res?.statusCode === SUCCESS_CODE) {
    ElMessage.success('操作成功')
    emit('dialogConfirmEvent')
    handleClose()
  }
  submitLoading.value = false
}

</script>

<style scoped lang="scss">
@import '@/styles/drawer-base-form.scss';
.tree-wrap{
  background: #f2f2f2;
  padding: 10px;
}
</style>
